package user

import (
	"context"
	"github.com/gin-gonic/gin"
	"net/http"
	common "project-common"
	"project-common/errs"
	loginServiceV1 "project-user/pkg/service/login.service.v1"
	user_service_v1 "project-user/pkg/service/user.service.v1"
	"strconv"
	"time"
)

type HandlerUser struct {
}

func New() *HandlerUser {
	return &HandlerUser{}
}

func (h *HandlerUser) getCaptcha(ctx *gin.Context) {
	result := &common.Result{}

	mobile := ctx.PostForm("mobile")
	c, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()
	rsp, err := loginServiceClient.GetCaptcha(c, &loginServiceV1.CaptchaRequest{Mobile: mobile})
	if err != nil {
		code, msg := errs.ParseGrpcError(err)
		ctx.JSON(http.StatusOK, result.Fail(code, msg))
		return
	}
	ctx.JSON(http.StatusOK, result.Success(rsp.Code))
}

func (h *HandlerUser) GetUserInfo(ctx *gin.Context) {
	result := &common.Result{}

	userId := ctx.Query("userId")
	intUserId, err := strconv.ParseInt(userId, 10, 64)
	if err != nil {
		ctx.JSON(http.StatusOK, result.Fail(400, "用户ID参数错误"))
		return
	}

	userResponse, err := userServiceClient.GetUserById(context.Background(), &user_service_v1.UserRequest{UserId: intUserId})
	if err != nil {
		code, msg := errs.ParseGrpcError(err)
		ctx.JSON(http.StatusOK, result.Fail(code, msg))
		return
	}
	ctx.JSON(http.StatusOK, result.Success(userResponse))
	// ctx.JSON(http.StatusOK, result.Success(nil))
}
